import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { FastifyReply } from 'fastify';
import winstonLogger from '../common/logger/winston.config';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
	intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
		const request = context.switchToHttp().getRequest<IRequest>();
		const response = context.switchToHttp().getResponse<FastifyReply>();
		const { method, url, ip } = request;
		const userAgent = request.headers['user-agent'] || '';

		// 获取请求参数
		const queryParams = request.query;
		const bodyParams = request.body;
		const params = request.params;

		// 获取 user 和 trackId
		const user = request.user ? JSON.stringify(request.user) : 'Not authenticated';
		const trackId = request.trackId || 'No trackId';

		const now = Date.now();

		return next.handle().pipe(
			tap(() => {
				const responseTime = Date.now() - now;
				const statusCode = response.statusCode;

				const logMessage = `
Request: ${method} ${url}
Status: ${statusCode}
Response Time: ${responseTime}ms
User Agent: ${userAgent}
IP: ${ip}
Query Params: ${JSON.stringify(queryParams)}
Body Params: ${JSON.stringify(bodyParams)}
Route Params: ${JSON.stringify(params)}
User: ${user}
TrackId: ${trackId}
				`.trim();

				winstonLogger.info(logMessage,{service:'LoggingInterceptor'});
			})
		);
	}
}
